package cbfg.http.demo.wanandroid

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.widget.AdapterView
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import cbfg.http.HttpManager
import cbfg.http.demo.GsonHolder
import cbfg.http.demo.R
import cbfg.http.demo.wanandroid.entity.Account
import cbfg.http.demo.wanandroid.entity.ArticleListEntity
import cbfg.http.demo.wanandroid.entity.BaseWanEntity
import cbfg.http.demo.wanandroid.entity.OfficialAccount
import cbfg.http.subscribe.Disposable
import kotlinx.android.synthetic.main.dialog_wan.view.*
import kotlinx.android.synthetic.main.fragment_wan.*

/**
 * @author:  Tom Hawk
 * 添加时间: 2020/9/22 14:20
 * 功能描述:
 */
class WanFragment : Fragment(R.layout.fragment_wan),
    AdapterView.OnItemSelectedListener {

    private lateinit var adapter: OfficialAcctAdapter

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        adapter = OfficialAcctAdapter(view.context)
        spAccounts.adapter = adapter
        spAccounts.onItemSelectedListener = this

        spPages.onItemSelectedListener = this
        tvResult.movementMethod = ScrollingMovementMethod.getInstance()

        btnRegister.setOnClickListener { showInputDialog(true) }
        btnLogin.setOnClickListener { showInputDialog(false) }

        fetchOfficialAccounts()
    }

    private fun showInputDialog(ifRegister: Boolean) {
        val context = requireContext()
        val layoutView = LayoutInflater.from(context).inflate(R.layout.dialog_wan, null)
        AlertDialog.Builder(context)
            .setTitle(if (ifRegister) "注册" else "登录")
            .setView(layoutView)
            .setPositiveButton("OK") { dialog, _ ->
                dialog.dismiss()
                loginOrRegister(
                    ifRegister,
                    layoutView.etUsername.text.toString(),
                    layoutView.etPassword.text.toString()
                )
            }
            .create()
            .show()
    }

    private fun loginOrRegister(ifRegister: Boolean, username: String, password: String) {
        val observer = if (ifRegister) {
            HttpManager.getService(WanService::class.java)
                .register(username, password, password)
        } else {
            /*
            //方法一：
            HttpManager.getService(WanService::class.java)
                .login(username, password)
            */
            //方法二：
            HttpManager.getService(WanService::class.java)
                .login(Account(username, password))
        }
        observer.subscribe(object : WanObserver<String>() {
            override fun onSubscribe(disposable: Disposable) {
                super.onSubscribe(disposable)
                tvResult.text = null
            }

            override fun onSuccess(result: String) {
                tvResult.text = result
            }

            override fun onError(e: Throwable) {
                tvResult.text = e.message
            }
        })
    }

    override fun onNothingSelected(parent: AdapterView<*>?) {}
    override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        //fetchArticles()
        fetchArticles2()
    }

    private fun fetchArticles2() {
        if (adapter.isEmpty) {
            return
        }
        HttpManager.getService(WanService::class.java)
            .getAccountArticles2(
                adapter.getItem(spAccounts.selectedItemPosition).id,
                spPages.selectedItem.toString()
            )
            .subscribe(object : WanObserver<String>(lifecycle) {
                override fun onSubscribe(disposable: Disposable) {
                    super.onSubscribe(disposable)
                    tvResult.text = null
                }

                override fun onSuccess(result: String) {
                    tvResult.text = result
                }

                override fun onError(e: Throwable) {
                    tvResult.text = e.message
                }
            })
    }


    private fun fetchArticles() {
        if (adapter.isEmpty) {
            return
        }
        HttpManager.getService(WanService::class.java)
            .getAccountArticles(
                adapter.getItem(spAccounts.selectedItemPosition).id,
                spPages.selectedItem.toString()
            )
            .subscribe(object : WanObserver<BaseWanEntity<ArticleListEntity>>(lifecycle) {
                override fun onSubscribe(disposable: Disposable) {
                    super.onSubscribe(disposable)
                    tvResult.text = null
                }

                override fun onSuccess(result: BaseWanEntity<ArticleListEntity>) {
                    tvResult.text = GsonHolder.gson.toJson(result)
                }

                override fun onError(e: Throwable) {
                    tvResult.text = e.message
                }
            })
    }

    private fun fetchOfficialAccounts() {
        HttpManager.getService(WanService::class.java)
            .getOfficialAccounts()
            .subscribe(object : WanObserver<BaseWanEntity<List<OfficialAccount>>>(lifecycle) {
                override fun onSuccess(result: BaseWanEntity<List<OfficialAccount>>) {
                    adapter.setItems(result.data)
                }

                override fun onError(e: Throwable) {
                    tvResult.text = e.message
                }
            })
    }
}